package com.moleq.itemsetting.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.moleq.models.NetworkSetting;
import com.moleq.network.CommTask;
import com.moleq.network.CommTaskParser;

/** */
/**
 * 
 * ��������������TXT�ļ������ж���д���޸Ĳ���
 * 
 * @author <a href="mailto:zhanghhui@126.com">KenZhang</a>
 * @version 1.0 Creation date: 2007-12-18 - ����06:48:45
 */
public class ReadWriteFile {
	public BufferedReader bufread;
	// ָ���ļ�·�������
	private String path = "";
	private File filename = null;
	private String readStr = "";

	public ReadWriteFile() {

	}

	/** */
	/**
	 * �����ı��ļ�.
	 * 
	 * @throws IOException
	 * 
	 */
	// "/mnt/sdcard/moleq/cache/sample.txt",
	// "/mnt/sdcard/moleq/cache/sample_modify.txt"
	public void creatTxtFile(String type) throws IOException {
		// if (!filename.exists()) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmssSSS");
		path = "/mnt/sdcard/moleq/cache/" + "{"
				+ formatter.format(new Date()) + "}{" + type + "}.txt";
		// path = "/mnt/sdcard/moleq/cache/cache" + "{"
		// + formatter.format(new Date()) + "}.txt";
		filename = new File(this.path);
		filename.createNewFile();
		// System.err.println(filename + "�Ѵ�����");
		// }
	}
	
//	public void checkSign(String str){
//		byte[] bytes = str.getBytes();
//		for (int i = 0; i < bytes.length; i++) {
//			if(bytes[i].equals("'")){
//				
//			}
//		}
//	}

	/** */
	/**
	 * ��ȡ�ı��ļ�.
	 * 
	 * @throws FileNotFoundException
	 * 
	 */

	public boolean checkDBStructure() throws FileNotFoundException {
		String read;
		FileReader fileread;
		fileread = new FileReader(filename);
		bufread = new BufferedReader(fileread);
		try {
			read = bufread.readLine();
			if (read == null) {
				fileread.close();
				bufread.close();
				return false;
			} else if (!read.substring(0, 9).equals("DataBase:")) {
				fileread.close();
				bufread.close();
				return false;
			} else {
				fileread.close();
				bufread.close();
				return true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public String readTxtFile() {
		String read;
		FileReader fileread;
		try {
			fileread = new FileReader(filename);
			bufread = new BufferedReader(fileread);
			try {
				while ((read = bufread.readLine()) != null) {
					readStr = readStr + read + "\r\n";
				}
				fileread.close();
				bufread.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// System.out.println("�ļ�������:" + "\r\n" + readStr);
		return readStr;
	}

	public List<String> readLine() {
		List<String> line = new ArrayList<String>();
		String read;
		FileReader fileread;
		try {
			fileread = new FileReader(filename);
			bufread = new BufferedReader(fileread);
			try {
				while ((read = bufread.readLine()) != null) {
					line.add(read);
				}
				fileread.close();
				bufread.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return line;
	}

	/** */
	/**
	 * д�ļ�.
	 * 
	 */
	public void writeTxtFile(String newStr) throws IOException {
		// �ȶ�ȡԭ���ļ����ݣ�Ȼ�����д�����
		String filein = newStr + "\r\n" + readStr + "\r\n";
		RandomAccessFile mm = null;
		try {
			mm = new RandomAccessFile(filename, "rw");
			mm.writeBytes(filein);
		} catch (IOException e1) {
			// TODO �Զ���� catch ��
			e1.printStackTrace();
		} finally {
			if (mm != null) {
				try {
					mm.close();
				} catch (IOException e2) {
					// TODO �Զ���� catch ��
					e2.printStackTrace();
				}
			}
		}
	}

	public void writeAddTxtFile(String newStr) throws IOException {
		// File file = new File(path);
		BufferedWriter bw = new BufferedWriter(new FileWriter(filename, true));
		bw.write(newStr);
		bw.write("\r\n");
		bw.close();
	}

	/** */
	/**
	 * ���ļ���ָ�����ݵĵ�һ���滻Ϊ��������.
	 * 
	 * @param oldStr
	 *            ��������
	 * @param replaceStr
	 *            �滻����
	 */
	public void replaceTxtByStr(String oldStr, String replaceStr) {
		String temp = "";
		try {
			File file = new File(path);
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);
			StringBuffer buf = new StringBuffer();

			// �������ǰ�������
			for (int j = 1; (temp = br.readLine()) != null
					&& !temp.equals(oldStr); j++) {
				buf = buf.append(temp);
				buf = buf.append(System.getProperty("line.separator"));
			}

			// �����ݲ���
			buf = buf.append(replaceStr);

			// ������к��������
			while ((temp = br.readLine()) != null) {
				buf = buf.append(System.getProperty("line.separator"));
				buf = buf.append(temp);
			}

			br.close();
			FileOutputStream fos = new FileOutputStream(file);
			PrintWriter pw = new PrintWriter(fos);
			pw.write(buf.toString().toCharArray());
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void txtToXml(List<NetworkSetting> mNetWorkSettingList,
			String xmlPath) {
		List<CommTask> commTasks = new ArrayList<CommTask>();
		if (mNetWorkSettingList.size() > 0) {
			List<String> lists = readLine();
			if (lists.size() > 0) {
				String dbStructure = lists.get(0);

				dbStructure = dbStructure.substring(9, dbStructure.length());
				lists.remove(0);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (int i = 0; i < mNetWorkSettingList.size(); i++) {
					CommTask task = new CommTask();
					task.setIpAddress(mNetWorkSettingList.get(i).getNs_ip());
					task.setStation(mNetWorkSettingList.get(i).getNs_station());
					task.setCreateDateTime(sdf.format(new Date()));
					task.setDbStructure(dbStructure);
					task.setActions(lists);
					commTasks.add(task);
				}
				if (commTasks.size() > 0) {
					sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					CommTaskParser mCommTaskParser = new CommTaskParser();
					String errorString = "";
					for (int i = 0; i < commTasks.size(); i++) {

						String path = xmlPath + "Task_"
								+ commTasks.get(i).getStation() + "_"
								+ sdf.format(new Date()) + ".xml";
						try {
							mCommTaskParser.save(commTasks.get(i), path);
						} catch (Throwable e) {
							// TODO Auto-generated catch block
							errorString += e.getMessage() + " \n";
							System.out.print(e.getMessage());
						}
					}
				}
			}
		}
	}

	/** */
	/**
	 * main��������
	 * 
	 * @param s
	 * @throws IOException
	 */
	// public static void main(String[] s) throws IOException {
	// ReadWriteFile.creatTxtFile();
	// ReadWriteFile.readTxtFile();
	// ReadWriteFile.writeTxtFile("20080808:12:13");
	// // ReadWriteFile.replaceTxtByStr("ken", "zhang");
	// }
}
